package actionbean;

import java.util.ArrayList;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.SimpleMessage;
import net.sourceforge.stripes.action.UrlBinding;
import controller.CartCtrl;
import controller.SectionCtrl;
import entity.Section;

@UrlBinding(BaseActionBean.URI_FOR_BOOKMARKS
		+ "{$event}/{courseCode}/{sectionCode}/{sourcePath}")
public class CartActionBean extends BaseActionBean {

	// init parameters
	private String courseCode;
	private String sectionCode;

	// init controllers
	private SectionCtrl sectionCtrl = new SectionCtrl();
	private CartCtrl cartCtrl = new CartCtrl();

	public String getCourseCode() {
		return courseCode;
	}

	public void setCourseCode(String courseCode) {
		this.courseCode = courseCode;
	}

	public String getSectionCode() {
		return sectionCode;
	}

	public void setSectionCode(String sectionCode) {
		this.sectionCode = sectionCode;
	}

	@DefaultHandler
	public Resolution view() {
		return new RedirectResolution(URI_FOR_COURSES);
	}

	@HandlesEvent("add")
	public Resolution add() {

		cartCtrl.addToCart(courseCode, sectionCode, getLoggedInUserId());

		addBookmarkedFeedbackMessage();

		return new RedirectResolution(getSourcePath());
	}

	@HandlesEvent("delete")
	public Resolution delete() {

		cartCtrl.deleteSection(courseCode, sectionCode, getLoggedInUserId());

		addUnbookmarkedFeedbackMessage();

		return new RedirectResolution(getSourcePath());
	}

	private void addBookmarkedFeedbackMessage() {
		String viewTimetableLink = "<a href='"
				+ pathToResource(URI_FOR_TIMETABLE) + "'>Timetable</a>";
		if (getSourcePath().contains(URI_FOR_TIMETABLE)) {
			addFeedbackMessage(new SimpleMessage("Bookmarked {0} ({1}).",
					courseCode, sectionCode));
		} else {
			addFeedbackMessage(new SimpleMessage(
					"Bookmarked {0} ({1}). See {2}.", courseCode, sectionCode,
					viewTimetableLink));
		}
	}

	private void addUnbookmarkedFeedbackMessage() {
		String viewTimetableLink = "<a href='"
				+ pathToResource(URI_FOR_TIMETABLE) + "'>Timetable</a>";
		if (getSourcePath().contains(URI_FOR_TIMETABLE)) {
			addFeedbackMessage(new SimpleMessage("Unbookmarked {0} ({1}).",
					courseCode, sectionCode));
		} else {
			addFeedbackMessage(new SimpleMessage(
					"Unbookmarked {0} ({1}). See {2}.", courseCode,
					sectionCode, viewTimetableLink));
		}
	}

	public ArrayList<Section> getSectionsInCart() {
		return cartCtrl.retrieveSectionsForStudent(getLoggedInUserId());
	}

}
